package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.domain.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lk
 * @date 2022-04-01
 */
@DubboService
public class UserLikeApiImpl implements UserLikeApi{
    @Autowired
    private MongoTemplate mongoTemplate;

    //保存喜欢数据
    @Override
    public Boolean saveOrUpdate(Long likeUserId,Long userId,boolean isLike) {
        try {
            //查询喜欢数据是否存在
            Query query =Query.query(Criteria.where("likeUserId").is(likeUserId).and("userId").is(userId));
            boolean exists = mongoTemplate.exists(query, UserLike.class);
            //不存在则保存
            if (exists){
                UserLike userLike = new UserLike();
                userLike.setIsLike(isLike);
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setCreated(System.currentTimeMillis());
                mongoTemplate.save(userId);
            }else{
                //存在则修改
                Update update = Update.update("isLike",isLike)
                        .set("updated",System.currentTimeMillis());
                mongoTemplate.updateFirst(query,update,UserLike.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //互相喜欢，喜欢，粉丝 - 统计
    @Override
    public Map findCountAll(Long userId) {
        Map map = new HashMap();
       //喜欢
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("isLike").is(true));
        List<UserLike> loveCount = mongoTemplate.find(query1, UserLike.class);
        //粉丝
        Query query2 = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(true));
        List<UserLike> fanCount = mongoTemplate.find(query2, UserLike.class);
        //拿出所有 我喜欢的id 和 粉丝的id
        List<Long> userIds = CollUtil.getFieldValues(fanCount, "likeUserId", Long.class);
        List<Long> list = CollUtil.getFieldValues(fanCount, "userId", Long.class);
        map.put("loveCount",userIds);
        map.put("fanCount",list);
        return map;
    }
}
